package com.tuozixuan;

import java.util.HashMap;
import java.util.Map;

import com.googlecode.aviator.AviatorEvaluator;
import com.googlecode.aviator.Expression;
import com.googlecode.aviator.runtime.function.AbstractFunction;
import com.googlecode.aviator.runtime.function.FunctionUtils;
import com.googlecode.aviator.runtime.type.AviatorBigInt;
import com.googlecode.aviator.runtime.type.AviatorObject;

/**
 * 自定义函数的使用
 */
public class AviatorCustomFunctionDemo {

	public static void main(String[] args) {
		AviatorEvaluator.addFunction(new MinFunction());
		String expression = "min(a,b)";
        Expression compiledExp = AviatorEvaluator.compile(expression, true);
        Map<String, Object> env = new HashMap<>();
        env.put("a", 100.3);
        env.put("b", 45);
        Double result = (Double) compiledExp.execute(env);
        System.out.println(result);
	}

}

class MinFunction extends AbstractFunction {

	private static final long serialVersionUID = -3121758065227180250L;

	@Override
	public AviatorObject call(final Map<String, Object> env, final AviatorObject arg1, final AviatorObject arg2) {
		Number left = FunctionUtils.getNumberValue(arg1, env);
		Number right = FunctionUtils.getNumberValue(arg2, env);
		return new AviatorBigInt(Math.min(left.doubleValue(), right.doubleValue()));
	}

	@Override
	public String getName() {
		return "min";
	}

}